package com.zw.transition.controller;

import com.zw.transition.base.BaseController;
import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.User;
import com.zw.transition.util.FileUtils;
import com.zw.transition.util.QRCodeUtil;
import com.zw.transition.util.ServletUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
@RequestMapping("/barCodeAnalyzing")
public class BarCodeScanController extends BaseController {

    /**
     * 扫码
     */
    @GetMapping("/scan/{type}")
    public String scan(@PathVariable("type") Integer type, Model model) {
        model.addAttribute("type", type);
        return "barCodeScan";
    }

    /**
     * 扫码扫码返回
     */
    @ResponseBody
    @PostMapping("/analyzing")
    public JsonResult scan(MultipartFile multiFile, Integer scanType) {
        // 将MultipartFile文件转换成File类型的PNG格式文件
        // 创建一个临时文件用于存放传递过来的PNG类型的电子签名图片
        User u = (User) ServletUtils.getSession().getAttribute("user");
        String uploadPath = "E:/" + File.separator + "transition/" + File.separator + "upload/" + File.separator + "__temp/" + File.separator + u.getAccount() + "/";
        FileUtils.mkdirs(uploadPath);// 创建目录
        String tempPath1 = uploadPath + File.separator + "tempFile" + System.currentTimeMillis() + ".png";
        File tempFile = new File(tempPath1);
        String str = "";
        try {
            // 将传递过来的PNG图片内容放到临时文件中
            multiFile.transferTo(tempFile);
            str = QRCodeUtil.decode(tempPath1);
            System.out.println(str);
            tempFile.delete();
        } catch (Exception e) {
            tempFile.delete();
        }
        if ("".equals(str)) {
            return error();
        } else {
            return success().setData(str);
        }
    }
}
